<?php

namespace app\admin\controller\kuerp\statistic;

use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use app\admin\model\kuerp\GoodsType;
use \app\admin\model\department\Department as DepartmentModel;
use think\Db;
use fast\Tree;
/**
 * 产品报表
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * GoodsSalesSummary模型对象
     * @var \app\admin\model\kuerp\GoodsSalesSummary
     */
    protected $model = null;
    protected $childrenSales = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuerp\GoodsSalesSummary;
        //部门经理查看部门成员 上级部门能查看下级部门
        $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
        //转为职员id
        $this->childrenSales = $adminids ? (new StaffMember())->getStaffMemberIds($adminids) : [];

        $salelist = (new StaffMember())->getSaleList($this->childrenSales);
        $this->view->assign("saleList", $salelist);
        $saleLists = [];
        foreach ($salelist as $salelist_k=>$salelist_v){
            $saleLists[] = ['name'=>$salelist_v['name'],'value'=>$salelist_v['id']];
        }
        $this->assignconfig("saleLists", $saleLists);

        // $tree = Tree::instance();
        // $tree->init(Admin::getAllDepartmentsArray($this->auth->id,($this->auth->isSuperAdmin()||$this->auth->data_scope)?true:false), 'parent_id');
        // $departmentList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $orgindepartmentList = Admin::getAllDepartmentsTreeArray($this->auth->id, $this->auth->isSuperAdmin()||$this->auth->data_scope);
        $departmentList = [];
        foreach ($orgindepartmentList as $key => $value) {
            $departmentList[] = [
                'id' => $key,
                'name' => $value
            ];
        }
        $this->view->assign("departmentList", $departmentList);
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $where = [];
            $searchdata = input();
            if($searchdata){
                foreach ($searchdata as $k => &$v) {
                    if(!empty($v)){
                        if ($k=='sale_user'){
                            $where['sale_user'] = ['in', $v];
                        } else if ($k == 'times') {
                            $where['purchase_time'] = ['between', setTimes($v,'time')];
                        } else if ($k == 'department_id') {
                            $departmentids = DepartmentModel::getChildrenIds($v, true);
                            $adminids = Admin::getDepartmentAdminIds($departmentids);
                            $sales = (new StaffMember())->getStaffMemberIds($adminids);
                            $where['sale_user'] = ['in', $sales];
                        }
                    }
                }
            }
            if (!isset($where['sale_user']) && !$this->auth->isSuperAdmin()) {
                //部门经理查看部门成员 上级部门能查看下级部门
                $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
                //转为职员id
                if ($adminids) {
                    $sales = (new StaffMember())->getStaffMemberIds($adminids);
                    $where['sale_user'] = ['in', $sales];
                }
            }
            
            $list = Db::name('kuerp_goods_sales_info')
                ->where($where)
                ->field("goods_code,sum(number) as number,sum(all_money) as all_money")->group('goods_code')->select();
                // echo Db::name('kuerp_goods_sales_summary')->getLastSql();
            $data = [
                'name' => [],
                'price' => [],
                'number' => [],
            ];
            $count = [
                'number' => 0,
                'price' => 0
            ];
            $datelist = [
                'date' => [],
                'data' => [],
                'name' => [],
            ];
            if(!empty($list)){
                $goods_codes = array_column($list,'goods_code');
                $goodslist = Db::name('kuerp_goods')->where(['goods_code'=> ['in', $goods_codes]])->column('goods_name', 'goods_code');
                //按日期 按产品 group by purchase_time,goods_code 
                //根据日期天数 判断是按天， 月 group by purchase_time,goods_code
                if (!empty($searchdata['times']) && !in_array($searchdata['times'],['today','yesterday'])){
                    $times = setTimes($searchdata['times'],'time');
                    $days = ceil(($times[1]-$times[0])/86400);
                    $fields = 'goods_code,sum(number) as number,sum(all_money) as all_money';
                    $dates = [];
                    if($days <= 31){
                        $fields = 'goods_code,sum(number) as number,sum(all_money) as all_money,DATE_FORMAT(FROM_UNIXTIME(purchase_time), \'%Y%m%d\') as date';
                        $start = strtotime(date('Y-m-d', $times[0]));
                        $end = strtotime(date('Y-m-d', $times[1]));
                        $dates = [];
                        for($i = $start; $i <= $end; $i += 86400) {
                            $dates[] = date('Ymd', $i);
                        }
                    }else {
                        $fields = 'goods_code,sum(number) as number,sum(all_money) as all_money, DATE_FORMAT(FROM_UNIXTIME(purchase_time), \'%Y%m\') as date';
                        // 生成月份数组
                        $start = date('Ym', $times[0]);
                        $end = date('Ym', $times[1]); 
                        $dates = [];
                        while($start <= $end) {
                            $dates[] = $start;
                            $start = date('Ym', strtotime($start . '01 +1 month'));
                        }
                    }
                    $group = 'goods_code,date';
                    $datelist['date'] = $dates;
                    $datelist['name'] = $goodslist;
                    $grouplist = Db::name('kuerp_goods_sales_info')->where($where)->field($fields)->group($group)->order('date')->select();
                    // echo Db::name('kuerp_goods_sales_info')->getLastSql();
                    $newgrouplist = [];
                    foreach ($grouplist as $grouplist_k=>$grouplist_v){
                        $newgrouplist[$grouplist_v['goods_code']][$grouplist_v['date']]['number'] = $grouplist_v['number'];
                        $newgrouplist[$grouplist_v['goods_code']][$grouplist_v['date']]['price'] = round($grouplist_v['all_money'],2);
                    }
                    foreach ($goodslist as $goodslist_k=>$goodslist_v){
                        $datelist['data'][$goodslist_k] = [];
                        foreach ($dates as $dates_k=>$dates_v){
                            $datelist['data'][$goodslist_k][$dates_v] = $newgrouplist[$goodslist_k][$dates_v] ?? ['number'=>0,'price'=>0];
                        }
                    }
                }
                foreach ($list as $list_k=>$list_v){
                    $data['name'][] = $goodslist[$list_v['goods_code']] ?? '';
                    $data['price'][] = round($list_v['all_money'],2);
                    $data['number'][] = $list_v['number'];
                    // $list[$list_k]['name'] = $goodslist[$list_v['goods_code']] ?? '';
                    // $list[$list_k]['price'] = round($list_v['all_money'],2);
                    $count['number'] += $list_v['number'];
                    $count['price'] += $list_v['all_money'];
                }
                $count['price'] = round($count['price'],2);
            }

            return json(['title' => '产品销量统计分析', 'data' => $data, 'count' => $count, 'datelist' => $datelist]);
        }
        return $this->view->fetch();
    }

}
